<template>
  <view class="apply-container">
    <!-- 状态提示 -->
    <view v-if="form.auditStatus === '1' || form.auditStatus === 1" class="status-notice approved-notice">
      <text class="notice-icon">✓</text>
      <text class="notice-text">您的申请已通过审核</text>
    </view>
    <view v-else-if="form.auditStatus === '2' || form.auditStatus === 2" class="status-notice rejected-notice">
      <text class="notice-icon">!</text>
      <text class="notice-text">申请需要修改，请重新提交</text>
    </view>
    <view v-else-if="form.auditStatus === '0' || form.auditStatus === 0" class="status-notice pending-notice">
      <text class="notice-icon">⏳</text>
      <text class="notice-text">申请审核中，请耐心等待</text>
    </view>
    <view v-else-if="isEdit" class="status-notice info-notice">
      <text class="notice-icon">ℹ</text>
      <text class="notice-text">加载已有申请，可继续修改</text>
    </view>

    <!-- 审核意见 -->
    <view v-if="(form.auditStatus === '1' || form.auditStatus === 1 || form.auditStatus === '2' || form.auditStatus === 2) && form.auditOpinion" class="audit-opinion-section">
      <view class="opinion-title">
        <text class="opinion-icon">📝</text>
        <text>审核意见</text>
      </view>
      <view class="opinion-content">{{ form.auditOpinion }}</view>
    </view>

    <view class="form-section" :class="{ 'disabled-form': isApproved }">
      <view class="form-title">入党积极分子申请{{ isEdit ? '（修改）' : '' }}</view>
      
      <view class="form-group">
        <view class="form-label required">入党申请书</view>
        <view class="upload-box" @click="uploadFile('applicationFile')">
          <view v-if="!form.applicationFile" class="upload-placeholder">
            <text class="iconfont icon-upload"></text>
            <text class="upload-text">点击上传入党申请书</text>
          </view>
          <view v-else class="file-info">
            <text class="iconfont icon-file"></text>
            <text class="file-name">{{ getFileName(form.applicationFile) }}</text>
          </view>
        </view>
      </view>

      <view class="form-group">
        <view class="form-label required">思想汇报</view>
        <view class="upload-box" @click="uploadFile('ideologicalReport')">
          <view v-if="!form.ideologicalReport" class="upload-placeholder">
            <text class="iconfont icon-upload"></text>
            <text class="upload-text">点击上传思想汇报</text>
          </view>
          <view v-else class="file-info">
            <text class="iconfont icon-file"></text>
            <text class="file-name">{{ getFileName(form.ideologicalReport) }}</text>
          </view>
        </view>
      </view>

      <view class="form-group">
        <view class="form-label required">推荐材料</view>
        <view class="upload-box" @click="uploadFile('recommendationFile')">
          <view v-if="!form.recommendationFile" class="upload-placeholder">
            <text class="iconfont icon-upload"></text>
            <text class="upload-text">点击上传推荐材料</text>
          </view>
          <view v-else class="file-info">
            <text class="iconfont icon-file"></text>
            <text class="file-name">{{ getFileName(form.recommendationFile) }}</text>
          </view>
        </view>
      </view>

      <view class="form-group">
        <view class="form-label required">申请日期</view>
        <picker mode="date" :value="form.applicationDate" @change="onDateChange">
          <view class="date-picker">
            <text v-if="form.applicationDate">{{ form.applicationDate }}</text>
            <text v-else class="placeholder">请选择申请日期</text>
          </view>
        </picker>
      </view>

      <view class="form-group">
        <view class="form-label">备注</view>
        <textarea 
          v-model="form.remark" 
          class="textarea-input" 
          placeholder="请输入备注信息"
          maxlength="500"
        ></textarea>
      </view>
    </view>

    <view class="button-group">
      <button v-if="!isApproved" class="submit-btn" @click="handleSubmit">
        {{ isEdit ? '修改申请' : '提交申请' }}
      </button>
      <button class="cancel-btn" @click="handleCancel">{{ isApproved ? '返回' : '取消' }}</button>
    </view>
  </view>
</template>

<script>
  import { addActivist, updateActivist, listActivist } from "@/api/system/party"
  import { uploadPartyFile } from "@/api/system/party"

  export default {
    data() {
      return {
        form: {
          activistId: null,  // 记录ID，用于判断是新增还是修改
          userId: null,
          applicationFile: '',
          ideologicalReport: '',
          recommendationFile: '',
          applicationDate: '',
          remark: '',
          auditStatus: null,  // 审核状态：0-待审核，1-已通过，2-需修改
          auditOpinion: ''
        },
        currentUploadField: '',
        isEdit: false,  // 是否为编辑模式
        isApproved: false,  // 是否已通过（已通过则禁止编辑）
        existingRecord: null  // 已存在的记录
      }
    },
    onLoad() {
      this.form.userId = this.$store.state.user.id
      // 设置默认日期为今天
      const today = new Date()
      this.form.applicationDate = this.formatDate(today)
      // 检查是否已有申请记录
      this.checkExistingRecord()
    },
    methods: {
      // 检查已有申请记录
      checkExistingRecord() {
        const userId = this.$store.state.user.id
        if (!userId) return

        uni.showLoading({ title: '加载中...' })
        
        listActivist({ userId: userId }).then(response => {
          uni.hideLoading()
          if (response.rows && response.rows.length > 0) {
            // 已有记录
            this.existingRecord = response.rows[0]
            this.isEdit = true
            this.form.activistId = this.existingRecord.activistId
            this.form.auditStatus = this.existingRecord.auditStatus
            
            // 判断是否已通过（已通过则不允许编辑）
            if (this.existingRecord.auditStatus === '1' || this.existingRecord.auditStatus === 1) {
              this.isApproved = true
            }
            
            // 加载已有数据
            this.loadExistingData()
          }
        }).catch(error => {
          uni.hideLoading()
          console.error('检查申请记录失败:', error)
        })
      },

      // 加载已有数据
      loadExistingData() {
        if (!this.existingRecord) return
        
        this.form.applicationFile = this.existingRecord.applicationFile || ''
        this.form.ideologicalReport = this.existingRecord.ideologicalReport || ''
        this.form.recommendationFile = this.existingRecord.recommendationFile || ''
        this.form.applicationDate = this.existingRecord.applicationDate || ''
        this.form.remark = this.existingRecord.remark || ''
        this.form.auditOpinion = this.existingRecord.auditOpinion || ''
        
        console.log('加载的审核状态:', this.form.auditStatus, typeof this.form.auditStatus)
        console.log('加载的审核意见:', this.form.auditOpinion)
      },

      // 上传文件
      uploadFile(fieldName) {
        // 如果已通过审核，禁止上传
        if (this.isApproved) {
          uni.showToast({
            title: '申请已通过，无法修改',
            icon: 'none'
          })
          return
        }
        
        this.currentUploadField = fieldName
        
        // 微信小程序使用 wx.chooseMessageFile
        // #ifdef MP-WEIXIN
        wx.chooseMessageFile({
          count: 1,
          type: 'file',
          success: (res) => {
            const tempFile = res.tempFiles[0]
            const tempFilePath = tempFile.path
            const fileName = tempFile.name  // 获取原始文件名
            this.doUpload(tempFilePath, fileName)
          },
          fail: (err) => {
            console.error('选择文件失败:', err)
            this.$modal.msgError('选择文件失败')
          }
        })
        // #endif
        
        // 其他平台使用 uni.chooseFile 或 uni.chooseImage
        // #ifndef MP-WEIXIN
        uni.chooseImage({
          count: 1,
          sourceType: ['album', 'camera'],
          success: (res) => {
            const tempFilePath = res.tempFilePaths[0]
            // 从路径中提取文件名
            const fileName = tempFilePath.substring(tempFilePath.lastIndexOf('/') + 1)
            this.doUpload(tempFilePath, fileName)
          },
          fail: (err) => {
            console.error('选择文件失败:', err)
            this.$modal.msgError('选择文件失败')
          }
        })
        // #endif
      },

      // 执行文件上传
      doUpload(filePath, fileName) {
        uni.showLoading({ title: '上传中...' })
        
        uploadPartyFile({
          name: 'file',
          filePath: filePath,
          formData: {
            originalFileName: fileName  // 传递原始文件名
          }
        }).then(response => {
          uni.hideLoading()
          if (response.code === 200) {
            this.form[this.currentUploadField] = response.url
            this.$modal.msgSuccess('上传成功')
          } else {
            this.$modal.msgError(response.msg || '上传失败')
          }
        }).catch(error => {
          uni.hideLoading()
          console.error('上传失败:', error)
          this.$modal.msgError('上传失败')
        })
      },

      // 日期选择
      onDateChange(e) {
        this.form.applicationDate = e.detail.value
      },

      // 格式化日期
      formatDate(date) {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
      },

      // 获取文件名
      getFileName(url) {
        if (!url) return ''
        const parts = url.split('/')
        return parts[parts.length - 1]
      },

      // 表单验证
      validateForm() {
        if (!this.form.applicationFile) {
          this.$modal.msgError('请上传入党申请书')
          return false
        }
        if (!this.form.ideologicalReport) {
          this.$modal.msgError('请上传思想汇报')
          return false
        }
        if (!this.form.recommendationFile) {
          this.$modal.msgError('请上传推荐材料')
          return false
        }
        if (!this.form.applicationDate) {
          this.$modal.msgError('请选择申请日期')
          return false
        }
        return true
      },

      // 提交申请
      handleSubmit() {
        // 如果已通过审核，禁止提交
        if (this.isApproved) {
          uni.showToast({
            title: '申请已通过，无法修改',
            icon: 'none'
          })
          return
        }

        if (!this.validateForm()) {
          return
        }

        // 准备提交数据
        const submitData = {
          ...this.form,
          userId: this.$store.state.user.id
        }

        // 如果是修改申请，将审核状态重置为待审核
        if (this.isEdit) {
          submitData.auditStatus = '0'
          submitData.auditOpinion = ''
        }

        // 根据是否有记录ID决定调用新增还是修改接口
        const apiMethod = this.isEdit ? updateActivist : addActivist
        const actionText = this.isEdit ? '修改' : '提交'

        uni.showLoading({ title: actionText + '中...' })
        
        apiMethod(submitData).then(response => {
          uni.hideLoading()
          if (response.code === 200) {
            this.$modal.msgSuccess(actionText + '成功')
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          } else {
            this.$modal.msgError(response.msg || actionText + '失败')
          }
        }).catch(error => {
          uni.hideLoading()
          console.error(actionText + '失败:', error)
          this.$modal.msgError(actionText + '失败')
        })
      },

      // 取消
      handleCancel() {
        uni.navigateBack()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .apply-container {
    min-height: 100vh;
    background-color: #f5f6f7;
    padding: 15px;
    padding-bottom: 80px;

    .status-notice {
      border-radius: 12px;
      padding: 15px 20px;
      margin-bottom: 15px;
      display: flex;
      align-items: center;
      color: #ffffff;

      .notice-icon {
        font-size: 24px;
        font-weight: bold;
        margin-right: 12px;
      }

      .notice-text {
        font-size: 16px;
        font-weight: 500;
      }
    }

    .approved-notice {
      background: linear-gradient(135deg, #52c41a 0%, #95de64 100%);
      box-shadow: 0 4px 12px rgba(82, 196, 26, 0.3);
    }

    .rejected-notice {
      background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);
      box-shadow: 0 4px 12px rgba(255, 77, 79, 0.3);
    }

    .pending-notice {
      background: linear-gradient(135deg, #fa8c16 0%, #ffa940 100%);
      box-shadow: 0 4px 12px rgba(250, 140, 22, 0.3);
    }

    .info-notice {
      background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
      box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
    }

    .disabled-form {
      opacity: 0.7;
      pointer-events: none;
    }

    /* 审核意见区域 */
    .audit-opinion-section {
      background-color: #ffffff;
      border-radius: 12px;
      padding: 15px 20px;
      margin-bottom: 15px;
      border-left: 4px solid #1890ff;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

      .opinion-title {
        display: flex;
        align-items: center;
        font-size: 15px;
        font-weight: bold;
        color: #333333;
        margin-bottom: 10px;

        .opinion-icon {
          margin-right: 6px;
          font-size: 16px;
        }
      }

      .opinion-content {
        font-size: 14px;
        color: #666666;
        line-height: 1.6;
        padding: 10px;
        background-color: #f5f7fa;
        border-radius: 8px;
        white-space: pre-wrap;
        word-break: break-all;
      }
    }

    .form-section {
      background-color: #ffffff;
      border-radius: 12px;
      padding: 20px;

      .form-title {
        font-size: 20px;
        font-weight: bold;
        color: #333333;
        margin-bottom: 20px;
        text-align: center;
      }

      .form-group {
        margin-bottom: 20px;

        .form-label {
          font-size: 14px;
          color: #333333;
          margin-bottom: 10px;

          &.required::before {
            content: '*';
            color: #ff4d4f;
            margin-right: 4px;
          }
        }

        .upload-box {
          border: 1px dashed #d9d9d9;
          border-radius: 8px;
          padding: 20px;
          text-align: center;
          background-color: #fafafa;

          .upload-placeholder {
            display: flex;
            flex-direction: column;
            align-items: center;

            .iconfont {
              font-size: 32px;
              color: #999999;
              margin-bottom: 8px;
            }

            .upload-text {
              font-size: 14px;
              color: #666666;
            }
          }

          .file-info {
            display: flex;
            align-items: center;
            justify-content: center;

            .iconfont {
              font-size: 24px;
              color: #1890ff;
              margin-right: 8px;
            }

            .file-name {
              font-size: 14px;
              color: #333333;
            }
          }
        }

        .date-picker {
          border: 1px solid #d9d9d9;
          border-radius: 8px;
          padding: 12px 15px;
          background-color: #ffffff;
          font-size: 14px;
          color: #333333;

          .placeholder {
            color: #999999;
          }
        }

        .textarea-input {
          width: 100%;
          min-height: 100px;
          border: 1px solid #d9d9d9;
          border-radius: 8px;
          padding: 12px 15px;
          font-size: 14px;
          color: #333333;
          background-color: #ffffff;
          box-sizing: border-box;
        }
      }
    }

    .button-group {
      margin: 20px 15px;
      padding: 0;
      display: flex;
      gap: 15px;

      .submit-btn,
      .cancel-btn {
        flex: 1;
        padding: 8px 0;
        border-radius: 6px;
        font-size: 14px;
        border: none;
      }

      .submit-btn {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #ffffff;
      }

      .cancel-btn {
        background-color: #f5f5f5;
        color: #666666;
      }
    }
  }
</style>

